package com.metaverse.backend.web;

import com.metaverse.backend.enums.AuthorityName;
import com.metaverse.backend.repo.AuthorityRepo;
import com.metaverse.backend.security.Authority;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/authority")
@AllArgsConstructor
public class AuthorityController extends BaseController {
    private AuthorityRepo authorityRepo;

    @PreAuthorize("hasAnyRole('ADMIN','OPERATOR')")
    @GetMapping("/all")
    public List<Authority> all() {
        List<Authority> list = authorityRepo.findAll();
        list = list.stream().filter(authority -> {
            //不显示普通用户和铸造者
            if(authority.getName().equals(AuthorityName.ROLE_USER.name())
                || authority.getName().equals(AuthorityName.ROLE_MINTER.name())){
                return false;
            }
            return !authority.isHide();
        }).collect(Collectors.toList());
        return list;
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    public Authority save(Authority authority) {
        return authorityRepo.save(authority);
    }
}
